package com.mapforge.gui.tools;

import java.util.Iterator;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import com.mapforge.listener.TileLayerDeletionEvent;
import com.mapforge.listener.TileLayerDeletionListener;
import com.mapforge.listener.TileLayerSelectionEvent;
import com.mapforge.listener.TileLayerSelectionListener;
import com.mapforge.listener.TileSelectionEvent;
import com.mapforge.listener.TileSelectionListener;
import com.mapforge.listener.TileWriterChangeEvent;
import com.mapforge.listener.TileWriterChangeListener;
import com.mapforge.map.TileLayer;
import com.mapforge.map.tools.tilewriting.AbstractTileWriterTool;

/**
 * This button allows the user to interface with {@link AbstractTileWriterTool}
 * used in editing {@link TileLayer}.
 * 
 * @see TileWriterTool
 * @author Will Morrison
 * 
 */
public class TileWriterToolButton extends MapToolButton implements
		TileWriterChangeListener, TileSelectionListener,
		TileLayerSelectionListener, TileLayerDeletionListener {
	/**
	 * Default serial version ID, here to remove warnings.
	 */
	private static final long serialVersionUID = 1L;

	public TileWriterToolButton(ImageIcon icon, AbstractTileWriterTool tool) {
		super(icon, tool, (JPanel) (new SelectionToolControlPanel(tool)));
	}

	public void tileWriterChangePerformed(TileWriterChangeEvent event) {
		getTileWriterMapTool().setTileWriter(event.getTileWriter());
	}

	public AbstractTileWriterTool getTileWriterMapTool() {
		return (AbstractTileWriterTool) getMapTool();
	}

	public void tileSelectionPerformed(TileSelectionEvent e) {
		getTileWriterMapTool().setTileSelection(e.getTileSelection());
	}

	@Override
	public void tileLayerSelectionPerformed(TileLayerSelectionEvent event) {
		if (event.getNumberLayersSelected() == 1) {
			Iterator<TileLayer> it = event.iterator();
			getTileWriterMapTool().setTileLayer(it.next());
			this.setEnabled(true);
		} else {
			getTileWriterMapTool().setTileLayer(null);
		}
	}

	@Override
	public void tileLayerDeletionPerformed(TileLayerDeletionEvent event) {
		AbstractTileWriterTool tileWriterTool = this.getTileWriterMapTool();
		Iterator<TileLayer> it = event.getDeletedLayerIterator();
		while (it.hasNext()) {
			if (tileWriterTool.getTileLayer() == it.next()) {
				// this.setEnabled(false);
				tileWriterTool.setTileLayer(null);
			}
		}
	}
}